package com.qf.edu.service;

import com.alibaba.fastjson.JSONObject;
import com.qf.edu.Constants;
import com.qf.edu.bean.BlockHash;
import com.qf.edu.utils.Request;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 吾忆
 * @email: 2432605231@qq.com
 * @phone:13677982829
 * @desc:该类用于实现通过rpc调用比特币客户端的getbestblockhash
 * @DateTime: 2021/12/26 0:03
 **/

public class GetBestBlockHashService {
    //该方法用于请求bitcoin客户端的相应区块的
    public Object getBestBlockHash(){
        //准备rpc请求的用户身份信息
        String auth = Constants.BITCOIN_RPC_USER+":"+Constants.BITCOIN_RPC_PWD;
        //java中实现base64编码
        Base64.Encoder encoder = Base64.getEncoder();
        String authBase64 = encoder.encodeToString(auth.getBytes());

        //准备请求头信息
        Map<String,String> header = new HashMap<>();
        header.put("ContentType","application/json");
        header.put("Authorization","Basic "+authBase64);

        //准备要发送的rpc数据
        Map<String,Object> body = new HashMap<>();
        body.put("id",1001);
        body.put("method","getbestblockhash");
        body.put("params",null);
        body.put("json_rpc","2.0");
        //将map转换成byte[]
        byte[] bodybytes = JSONObject.toJSONBytes(body);

        //格式：{"id":1001,"result":xxxx,"error":null}
        String result = Request.post(Constants.BITCOIN_RPC_URL,header,bodybytes);
        //json解析
        BlockHash hash = JSONObject.parseObject(result, BlockHash.class);

        return hash.result;
    }

}
